using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SoundManager : MonoBehaviour
{
    private AudioSource bgmAudio;
    private AudioSource soundEffectAudio;

    private float bgmVolume
    {
        get { return PlayerPrefs.GetFloat("bgmVolume", 1.0f); }

        set
        {
            bgmAudio.volume = value;
            PlayerPrefs.SetFloat("bgmVolume", value);
        }
    }

    private float soundEffectVolume
    {
        get { return PlayerPrefs.GetFloat("soundEffectVolume", 1.0f); }

        set
        {
            soundEffectAudio.volume = value;
            PlayerPrefs.SetFloat("soundEffectVolume", value);
        }
    }

    private void Awake()
    {
        bgmAudio = this.gameObject.AddComponent<AudioSource>();
        bgmAudio.playOnAwake = false;
        bgmAudio.loop = true;

        soundEffectAudio = this.gameObject.AddComponent<AudioSource>();
        soundEffectAudio.loop = false;
    }

    #region 背景音乐控制模块

    public void PlayMusic(string _name)
    {
        if (this.bgmVolume < 0.1f)
            return;

        string oldname = "";

        if(bgmAudio.clip != null)
            oldname = bgmAudio.clip.name;

        if(oldname == _name)
        {
            bgmAudio.Play();
            return;
        }

        Manager.Resources.LoadMusic(_name, (UnityEngine.Object obj) =>
        {
            bgmAudio.clip = obj as AudioClip;
            bgmAudio.Play();
        });
    }

    public void PauseMusic()
    {
        bgmAudio?.Pause();
    }

    public void UnPauseMusic()
    {
        bgmAudio?.UnPause();
    }

    public void StopMusic()
    {
        bgmAudio?.Stop();
    }

    public void SetMusicVolume(float volume)
    {
        this.bgmVolume = volume;
    }

    #endregion

    #region 音效控制模块

    public void PlaySoundEffect(string _name)
    {
        if(this.soundEffectVolume < 0.1f) return;

        Manager.Resources.LoadSoundEffect(_name, (UnityEngine.Object obj) =>
        {
            soundEffectAudio.PlayOneShot(obj as AudioClip);
        });
    }

    public void SetSoundEffectVolume(float volume)
    {
        this.soundEffectVolume = volume;
    }

    #endregion
}
